package gps.monitor.jt809server.protocol.codec;

import gps.monitor.jt809server.entity.DownPlatformAccount;
import gps.monitor.jt809server.protocol.Jt809ProtocolFactory;
import gps.monitor.jt809server.protocol.model.AbstractJt809Message;
import gps.monitor.jt809server.protocol.Jt809ParseException;
import gps.monitor.jt809server.protocol.model.Jt809MessageHeader;
import gps.monitor.jt809server.protocol.model.Jt809UpExgMsgMessage;
import gps.monitor.jt809server.util.ProtocolUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.Data;

import java.nio.charset.Charset;

/**
 * @author cyq
 * @date 2021/11/7
 * @desc talk is cheep,show me the code
 */
@Data
public class Jt809Handler1200 implements IJt809Handler {


    @Override
    public AbstractJt809Message read(ByteBuf byteBuf, DownPlatformAccount account) throws Jt809ParseException {
        Jt809MessageHeader header = readGeneralHeader(byteBuf);
        if (header.getEncryptFlag() == 1) {
            ProtocolUtils.encryptBody(byteBuf, account.getM1(), account.getA1(), account.getC1(), header.getEncryptKey());
        }
        //获取dataType
        String hexDataType = ByteBufUtil.hexDump(byteBuf, byteBuf.readerIndex() + 22, 2);
        IJt809SubHandler subHandler = Jt809ProtocolFactory.getJt809SubHandler(hexDataType);
        if (subHandler == null) {
            return null;
        }

        if (subHandler instanceof Jt809UpExgMsgHandler) {
            Jt809UpExgMsgHandler upExgMsgHandler = (Jt809UpExgMsgHandler) subHandler;
            Jt809UpExgMsgMessage message = (Jt809UpExgMsgMessage) upExgMsgHandler.readBody(byteBuf);
            message.setHeader(header);
            return message;
        }

        return null;
    }
}
